#include "loggedinform.h"
#include "ui_loggedinform.h"

LoggedInForm::LoggedInForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoggedInForm)
{
    ui->setupUi(this);

    contactsModel_ = new QStringListModel(this);
    messagesModel_ = new QStringListModel(this);

    downloadTimer_ = NULL;

    contactsRequest_ = NULL;
    messagesRequest_ = NULL;
    postMessageRequest_ = NULL;
    contactsTask_ = NULL;
    messagesTask_ = NULL;
    postMessageTask_ = NULL;

    currentNumber_ = "";

    ui->listView->setModel(contactsModel_);
    ui->listView_2->setModel(messagesModel_);

    connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(onSendButtonClicked()));
    connect(ui->listView, SIGNAL(clicked(QModelIndex)), this, SLOT(onContactClicked(QModelIndex)));
}

void LoggedInForm::onLoginSuccess(QString cookieData)
{
    cookieData_ = cookieData;

    contactsRequest_ = new ContactsRequest(cookieData);
    contactsTask_ = new AsyncTask(contactsRequest_, this);

    messagesRequest_ = new MessagesRequest(cookieData);
    messagesTask_ = new AsyncTask(messagesRequest_);

    connect(contactsRequest_, SIGNAL(error(QString)), this, SLOT(error(QString)));
    connect(contactsRequest_, SIGNAL(responseStrings(QStringList, QStringList)), this, SLOT(onContactsRequestSuccess(QStringList, QStringList)));

    contactsTask_->execute();
}

void LoggedInForm::error(QString error)
{
    QMessageBox messageBox(QMessageBox::Warning, tr("Error"), error, QMessageBox::Ok, this);

    messageBox.exec();
}

void LoggedInForm::onContactsRequestSuccess(QStringList names, QStringList numbers)
{
    QStringList sortedNames(names);
    QStringList sortedNumbers;

    sortedNames.sort();

    for (int i = 0; i < sortedNames.size(); i++) {
        QString name = sortedNames.value(i);
        int index = names.indexOf(name);
        QString number = numbers.at(index);
        number = number.remove("\"");
        sortedNumbers.append(number);
    }

    names_ = sortedNames;
    numbers_ = sortedNumbers;

    contactsModel_->setStringList(names_);

    onTimerExpiration();

    downloadTimer_ = new QTimer(this);

    connect(downloadTimer_, SIGNAL(timeout()), this, SLOT(onTimerExpiration()));

    downloadTimer_->start(5000);
}

void LoggedInForm::onMessagesRequestSuccess(QHash<QString, QList<Message> > *data)
{
    QList<QString> keys(data->keys());

    qDebug() << data->size();

    for (int i = 0; i < keys.size(); i++) {
        QList<Message> newMessages = data->value(keys.at(i));
        QList<Message> existingMessages = messagesFromNumbers_.value(keys.at(i));

        existingMessages.append(newMessages);

        if (currentNumber_ == keys.at(i)) {
            QStringList messages;

            for (int j = 0; j < existingMessages.size(); j++) {
                Message message = existingMessages.at(j);
                messages.append(message.getMessageBody());
            }

            messagesModel_->setStringList(messages);
        }

        messagesFromNumbers_.insert(keys.at(i), existingMessages);
    }
}

void LoggedInForm::onContactClicked(QModelIndex modelIndex)
{
    QString name = modelIndex.data().toString();

    int index = names_.indexOf(name);

    QString number = numbers_.at(index);

    currentNumber_ = number;

    QList<Message> messages = messagesFromNumbers_.value(number);

    QStringList messagesList;

    for (int i = 0; i < messages.length(); i++) {
        Message message = messages.at(i);

        messagesList.append(message.getMessageBody());
    }

    messagesModel_->setStringList(messagesList);
}

void LoggedInForm::onSendButtonClicked()
{
    if (currentNumber_ != "") {
        QString message = ui->textEdit->toPlainText();
        ui->textEdit->clear();

        qDebug() << message;

        QList<Message> messages = messagesFromNumbers_.value(currentNumber_);

        messages.append(Message(message, 0));

        QStringList messagesList;

        for (int i = 0; i < messages.size(); i++) {
            Message message = messages.at(i);
            messagesList.append(message.getMessageBody());
        }

        messagesModel_->setStringList(messagesList);

        messagesFromNumbers_.insert(currentNumber_, messages);

        QString timestamp;
        QDateTime dateTime;
        dateTime.setTime(QTime::currentTime());

        timestamp = timestamp.number(dateTime.toMSecsSinceEpoch());

        postMessageRequest_ = new PostMessageRequest(currentNumber_, message, timestamp, cookieData_);
        postMessageTask_ = new AsyncTask(postMessageRequest_, this);

        connect(postMessageRequest_, SIGNAL(error(QString)), this, SLOT(error(QString)));

        postMessageTask_->execute();
    }
    else {
        QMessageBox msgBox(QMessageBox::Warning, tr("No Contact Selected"), tr("You must first select a contact"), QMessageBox::Ok, this);
        msgBox.setModal(true);
        msgBox.exec();
    }
}

void LoggedInForm::onTimerExpiration()
{
    messagesRequest_ = new MessagesRequest(cookieData_);
    messagesTask_ = new AsyncTask(messagesRequest_, this);

    connect(messagesRequest_, SIGNAL(error(QString)), this, SLOT(error(QString)));
    connect(messagesRequest_, SIGNAL(responseData(QHash<QString,QList<Message> >*)), this, SLOT(onMessagesRequestSuccess(QHash<QString,QList<Message> >*)));

    messagesTask_->execute();
}

LoggedInForm::~LoggedInForm()
{
    delete ui;
}
